<template>
<div class="approvalDetails">
    <div class="approvalDetails_header">
        <div class="approvalDetails_header_navBar">
            {{ isStatusName(lookData.auditStatus, status) }}
            <img class="approvalDetails_header_navBar_img" src="@/assets/porduct/zuo_jiantou.png" alt=""
                @click="routerBack">
        </div>
    </div>
    <ListItems class="approvalDetails_ListItems" :row="lookData" :status="status" @click="handleGetDetails()" />
    <div class="approvalDetails_box">
        <StepBar stepBarTitle="审批结果" :data="getStepBarData()" :auditStatus="lookData.auditStatus" :status="status"
            :hmMechanismsList="lookData.hmMechanismsList" />
    </div>

    <div class="approvalDetails_footer" v-if="isOperate(lookData.auditStatus, status)">
      <div class="bt_f_left" @click="onClickComplement">
        <div class="buma"></div>
        <div class="bt_text">补码</div>
      </div>

      <div class="footer_center" @click="onClickRight"
        v-if="user.user.indexOf('recruitContractAudit') == -1 && user.user.indexOf('recruitManage') == -1 && lookData.auditStatus !== '22' && lookData.auditStatus !== '20'">
        编辑
      </div>
      <div class="footer_center" @click="overlayShow = true"
        v-if="(user.user.indexOf('recruitContractAudit') != -1 || user.user.indexOf('recruitManage') != -1) && lookData.auditStatus === '22'">
        驳回</div>
      <div class="footer_right" @click="approvalClick()">
        <template v-if="loading">
          <van-loading type="spinner" size="24px" color="#fff"> 执行中...</van-loading>
        </template>
        <template v-else>
          {{ isButtonName() }}
        </template>
      </div>
    </div>
    <!-- 资质送审 -->
    <van-overlay :show="qualificationsFlag" z-index="2001">
      <div class="wrapper_qualifications" @click.stop>
        <div class="wrapper_div">
          <van-image class="close" :src="colseImg" @click="qualificationsFlag = false"></van-image>
          <div class="title">选择送审品类</div>
          <div class="describe">请为您的商品选择送审的品类</div>
          <div class="column">
            <div class="lable">可选品类</div>
            <div class="value" @click="categoryFlag = true">
              {{ categoryMessage || '请选择' }}
              <van-image :src="icon_heisexiasanjiao"></van-image>
            </div>
          </div>
          <van-popup v-model:show="categoryFlag" position="bottom">
            <van-picker title="可选品类" :columns="categoryColumns" @confirm="onConfirmCategory"
              @cancel="categoryFlag = false" />
          </van-popup>
          <div class="buttons">
            <div class="cancel" @click="qualificationsCancel">取消</div>
            <div class="save" @click="qualificationsSubmit">确定</div>
          </div>
        </div>
      </div>
    </van-overlay>
    <!-- 无合同驳回 -->
    <van-overlay :show="overlayShow" @click="overlayShow = false" z-index="6001">
      <div class="wrapper" @click.stop>
        <div class="wrapper_div">
          <van-image :src="colseImg" @click="close"></van-image>
          <div class="title">驳回建议</div>
          <van-form @submit="onSubmit">
            <van-field maxlength="50" show-word-limit v-model="message" rows="6" label="" type="textarea"
              placeholder="请输入驳回建议" :border="false" />
            <van-button class="button" :loading="loading" loading-text="执行中..." round block type="primary"
              native-type="submit" v-throttle:click>
              提交确认
            </van-button>
          </van-form>
        </div>
      </div>
    </van-overlay>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import ListItems from './components/listItemsNewui.vue' // 列表单个项
import StepBar from './components/stepBar/index.vue'  // 步骤条
import { getProductDetailed } from '@/api/productList/index'
import { userStore } from "@/store/user";
import { getSystemList } from '@/api/approval/index'
import { getInfo } from "@/api/supplierList/index";
import { reAuditSecond, editSevens, noContractUpdate } from "@/api/productList/index";
import { againStock } from '@/api/productHome/index.ts'
import { isStatusName } from './components/listItems.ts'
import { showFailToast, showSuccessToast } from "vant";
const colseImg = new URL("@/assets/approval/close.png", import.meta.url).href;
const icon_heisexiasanjiao = new URL("@/assets/productHome/icon_heisexiasanjiao.png", import.meta.url).href;

const route: any = useRoute()
const router = useRouter()
const user = userStore();
const showLoading = ref(false)
const status = ref()
const overlayShow = ref(false)
const message = ref('')

const lookData = ref<any>({})

const loading = ref(false)
// 资质审核显隐
const qualificationsFlag = ref(false)
// 资质审核可选品类值
const categoryMessage = ref()
// 资质审核可选品类id
const categoryId = ref()
// 资质审核可选品类显隐
const categoryFlag = ref(false)
// 资质审核可选品类column
const categoryColumns = ref([])
const categoryMap = {
  '鞋帽': '1',
  '酒茶': '2',
  '箱包': '3',
  '百货': '4',
  '服装': '5',
  '食品': '6'
}
/** 可选品类column */
const getcategoryColumns = async () => {
  const res = await getSystemList({ parentId: '1796913597400784898' })
  if (res.data.length) {
    // 去掉惠麦优选部门
    const response = res.data.filter(item => item.deptName !== '惠麦优选')
    response.forEach(item => {
      item.text = item.deptName
      Object.keys(categoryMap).forEach(key => {
        if (item.deptName.includes(key)) {
          item.value = categoryMap[key];
          return;
        }
      });
    })
    categoryColumns.value = response
  }
}
getcategoryColumns()
/** 可选品类筛选 */
const onConfirmCategory = ({ selectedOptions }) => {
  categoryMessage.value = selectedOptions[0]?.text;
  categoryId.value = selectedOptions[0]?.value;
  categoryFlag.value = false
}
/** 可选品类取消 */
const qualificationsCancel = async () => {
  categoryMessage.value = ''
  qualificationsFlag.value = false
}
/** 可选品类提交 */
const qualificationsSubmit = async () => {
  if (!categoryMessage.value) {
    showFailToast({ message: "请选择可选品类", teleport: '.wrapper_div' });
  } else {
    // 商品预审
    await editSevens({ ids: [lookData.value.id], productType: categoryId.value })
    showSuccessToast({ type: "success", message: "商品送审成功" });
    qualificationsFlag.value = false
    categoryMessage.value = ''
    showSuccessToast({ type: "success", message: "商品送审成功" });
    routerBack()
  }
}

// 从新送审按钮文字
const isButtonName = () => {
  if (lookData.value.auditStatus === '8' || lookData.value.auditStatus === '10' || lookData.value.auditStatus === '9') {
    return '发起初审'
  }
  if (lookData.value.auditStatus === '12') {
    return '价格复审'
  }
  if (lookData.value.auditStatus === '17') {
    return '重新入库'
  }
  if (lookData.value.auditStatus === '22') {
    return '同意'
  }
  if (lookData.value.auditStatus === '20') {
    return '变价审核'
  }
}
// 从新送审操作
const approvalClick = async () => {
  showLoading.value = true
  loading.value = true
  const type = isButtonName()
  if (type === '发起初审') {
    try {
      const data = await getInfo()
      if (data.data.user.dept.deptName != '食品部' && data.data.user.dept.deptName != '鞋帽部' && data.data.user.dept.deptName != '百货部' && data.data.user.dept.deptName != '酒茶部' && data.data.user.dept.deptName != '箱包部' && data.data.user.dept.deptName != '服装部') {
        qualificationsFlag.value = true
      } else {
        await editSevens({ ids: [lookData.value.id] })
        showSuccessToast({ type: "success", message: "商品送审成功" });
        loading.value = false
        routerBack()
      }
    } catch (error) {
      showLoading.value = false
      loading.value = false
    }
  }
  if (type === '价格复审') {
    try {
      await reAuditSecond({ id: lookData.value.id })
      showSuccessToast({ type: "success", message: "商品送审成功" });

      loading.value = false
      routerBack()
    } catch {
      showLoading.value = false
      loading.value = false
    }
  }
  if (type === '重新入库') {
    try {
      await againStock({ id: lookData.value.id });
      loading.value = false
      showSuccessToast({ type: "success", message: "产品重新入库中" });
      routerBack()
    } catch (error) {
      showLoading.value = false
      loading.value = false
    }
  }
  // 无合同审批同意
  if (type === '同意') {
    try {
      await noContractUpdate({
        id: lookData.value.contactId,
        productsId: lookData.value.id,
        auditingStatus: '2',
        auditDeptId: '',
      })
      loading.value = false
      showSuccessToast({ type: 'success', message: '审批成功' });
      routerBack()
    } catch (error) {
      showLoading.value = false
      loading.value = false
    }
  }
  // 无合同审批同意
  if (type === '变价审核') {
    router.push({
      path: '/mechanismPriceChange',
      query: {
        id: lookData.value.id
      }
    });
  }
  showLoading.value = false
  loading.value = false
}


// 需要展示步骤条的数据
const getStepBarData = () => {
  if (lookData.value.auditStatus === '7' || (lookData.value.auditStatus === '11' && status.value === 1) || lookData.value.auditStatus === '8' || lookData.value.auditStatus === '9' || lookData.value.auditStatus === '10') {
    // 8:初审全部驳回，9:初审中资质驳回，10:初审中的价格驳回，11并且status==1：初审通过
    return lookData.value.hmQualityProductsAuditLogVos
  } else if ((lookData.value.auditStatus === '11' && status.value === 0) || lookData.value.auditStatus === '12' || lookData.value.auditStatus === '13') {
    // 11并且status==0：复审中、12：复审驳回，13：复审通过
    return lookData.value.hmPricingProductsAuditLogLists
  } else if (lookData.value.auditStatus === '22' || lookData.value.auditStatus === '14' || lookData.value.auditStatus === '15') {
    // 22:无合同审批中，14：无合同审批驳回
    return lookData.value.hmContactLogList
  } else if (lookData.value.auditStatus === '18' || lookData.value.auditStatus === '16' || lookData.value.auditStatus === '17') {
    // 18：入库通过、变价通过,16：入库中
    return lookData.value.hmStockAuditLogList
  } else if (lookData.value.auditStatus === '19' || lookData.value.auditStatus === '20' || lookData.value.auditStatus === '21') {
    // 19：变审中，20：变价驳回，21：变审通过
    let data = lookData.value.hmChangeAuditLogVoList.filter(item => {
      return item.stockAuditStatus !== 2
    })
    return data
  }
}

/** 无合同审批驳回建议提交 */
const onSubmit = async () => {

  if (!message.value) {
    showFailToast({ message: "请输入驳回建议", teleport: '.wrapper_div' });
  } else {
    showLoading.value = true
    loading.value = true
    try {
      await noContractUpdate({
        id: lookData.value.contactId,
        productsId: lookData.value.id,
        auditingStatus: '1',
        auditDeptId: '',
        remark: message.value,
        recruiterRemark: lookData.value.recruiterRemark,
        supplementTime: lookData.value.supplementTime
      })
      loading.value = false
      message.value = ''
      showSuccessToast({ type: 'success', message: '驳回建议提交成功' });
      overlayShow.value = false
      showLoading.value = false
      routerBack()
    } catch (error) {
      if (error == 'timeout') {
        showFailToast('驳回建议提交失败');
      }
      loading.value = false
    }
  }
}

// 判断操作是否展示
const isOperate = (auditStatus, status) => {
  const type = isStatusName(auditStatus, status)
  return type === '初审驳回' || type === '复审驳回' || (type === '无合同审批中' && (user.user.indexOf('recruitContractAudit') != -1 || user.user.indexOf('recruitManage') != -1)) || type === '入库驳回' || type === '变价驳回'
}

/** 无合同审批驳回建议关闭 */
const close = () => {
  overlayShow.value = false
}

/** 补码跳转 */
const onClickComplement = () => {
  //  69码
  let styleCode = lookData.value.id;
  // 价格
  let price =
    lookData.value.hmMechanismsList[0].cooperationMode == "分佣"
      ? lookData.value.hmMechanismsList[0].price
      : lookData.value.hmMechanismsList[0].costPrice;
  // 佣金
  let commission =
    lookData.value.hmMechanismsList[0].cooperationMode == "分佣"
      ? lookData.value.hmMechanismsList[0].commission + "%"
      : "";
  // 机制
  let liveStreamingMechanism = lookData.value.hmMechanismsList[0].liveStreamingMechanism;
  // 商品名
  let styleName =
    lookData.value.styleName.length > 18
      ? lookData.value.styleName.substr(0, 18)
      : lookData.value.styleName;
  // 品牌名
  var brandName = lookData.value.brandName ? lookData.value.brandName : "";
  if (brandName.length > 18) {
    brandName = brandName.substr(0, 18);
  }
  // 上架时间
  let listingTime = lookData.value.shoppingTime ? "上架时间:" + lookData.value.shoppingTime : "上架时间:";
  // 规格/材质
  const gecs = lookData.value.specs ? lookData.value.specs : '';
  const specs = gecs.length > 190 ? gecs.substring(0, 190) : gecs
  let specsing =
    "规格/材质:" + specs;
  // 卖点
  let sellingPoint = "卖点:" + lookData.value.sellingPoints;
  //招商元姓名
  let recruiter = '招商:' + lookData.value.recruiter
  const arr: Array<string> = [];
  if (lookData.value.hmMechanismsList.length > 0) {
    lookData.value.hmMechanismsList.forEach((item, index) => {
      if (item.cooperationMode) {
        const obj = {
          title: index == 0 ? '机制一:' : index == 1 ? '机制二:' : '机制三:',
          number: item.cooperationMode == '分佣' ? `${item.price || 0.00}` : `${item.costPrice || 0.00}`,
          commission: item.cooperationMode == '分佣' ? `${item.commission || 0.00}%` : '',
          brokerage: item.cooperationMode == '分佣' ? `+${item.brokerage || 0.00}%` : '',
          liveStreamingMechanism: index == 0 ? item.liveStreamingMechanism || '' : item.liveStreamingMechanism.substring(0, 8) || ''
        }
        arr.push(obj.title)
        arr.push(obj.number)
        arr.push(obj.commission)
        arr.push(obj.brokerage)
        arr.push(obj.liveStreamingMechanism)
      }
    })
  }

  (window as any).uni.navigateTo({
    url: `/pages/print/index?barCode=${encodeURIComponent(
      styleCode
    )}&num1=${encodeURIComponent(price)}&num2=${encodeURIComponent(
      commission
    )}&num3=${encodeURIComponent(
      liveStreamingMechanism
    )}&name=${encodeURIComponent(styleName)}&brand=${encodeURIComponent(
      brandName
    )}&listingTime=${encodeURIComponent(
      listingTime
    )}&recruiter=${encodeURIComponent(
      recruiter
    )}&specsing=${encodeURIComponent(
      specsing
    )}&mechanismList=${encodeURIComponent(
      arr.join(',')
    )}&sellingPoint=${encodeURIComponent(sellingPoint)}&page=1&from=merchants`,
  });
};

/** 编辑 */
const onClickRight = () => {
  if (lookData.value.auditStatus === '9') {
    router.push(`/editProduct/${lookData.value.id}?correctMechanism=correctMechanism`);
  } else if (lookData.value.auditStatus === '17') {
    router.push(`/editProduct/${lookData.value.id}?fiveMechanism=fiveMechanism`);
  } else if (lookData.value.auditStatus === '10' || lookData.value.auditStatus === '12') {
    router.push(`/editProduct/${lookData.value.id}?mechanism=mechanism`);
  } else {
    router.push(`/editProduct/${lookData.value.id}`);
  }
};

// 返回
const routerBack = () => {
  router.back()
}

/** 获取详情 */
const handleGetDetails = () => {
  router.push({
    path: `/productDetail/${route?.query?.id}`,
  });
};

const getLook = async (id: any) => {
  showLoading.value = true
  const { data = {} } = await getProductDetailed({ id })
  lookData.value = data
  showLoading.value = false
}
onMounted(() => {
  status.value = Number(route?.query?.status)
  getLook(route?.query?.id)
})
</script>

<style lang="less" scoped>
.approvalDetails {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-flow: column;
  background: #f6f8fa;

  .approvalDetails_header {
    padding-top: 45px;
    background: linear-gradient(#CDECFF 0%, #FFFFFF 100%);
    margin-bottom: 10px;

    .approvalDetails_header_navBar {
      padding: 15px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: 500;
      font-size: 16px;
      color: #1A1B1C;
      position: relative;

      .approvalDetails_header_navBar_img {
        position: absolute;
        top: 50%;
        left: 15px;
        transform: translate(0%, -50%);
        width: 15px;
        height: 16px;
      }
    }
  }

  .approvalDetails_ListItems {
    margin-bottom: 15px;
  }

  .approvalDetails_box {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    padding: 0 15px 15px;
    box-sizing: border-box;
  }

  .approvalDetails_footer {
    width: 375px;
    height: 84px;
    background: #FFFFFF;
    box-shadow: 0px 0px 8px 0px rgba(189, 195, 204, 0.5);
    padding: 20px 15px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;

    
    .bt_f_left{
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-left: 15px;
      margin-right: 30px;
      .buma{
        width: 20px;
        height: 20px;
        background: url("@/assets/newui/details/icon_buma@2x.png");
        background-repeat: no-repeat;
        background-size: 100% 100%; 
      }
      .bt_text{
        font-weight: 400;
        font-size: 12px;
        color: #0094FF;
        line-height: 12px;
        margin-top: 6px;
      }
    }

    .footer_center {
      width: 0px;
      flex: 2;
      height: 100%;
      border-radius: 5px;
      border: 1px solid #5FBBFF;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: 400;
      font-size: 16px;
      color: #0094FF;
      margin-right:  10px;
    }

    .footer_right {
      width: 0px;
      flex: 3;
      height: 100%;
      background: linear-gradient(146deg, #0064FF 0%, #008FFF 100%);
      border-radius: 5px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: 500;
      font-size: 16px;
      color: #FFFFFF;
    }
  }
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;

  .wrapper_div {
    width: 315px;
    height: 317px;
    background-color: #fff;
    border-radius: 5px;
    position: relative;

    :deep .van-field__control {
      background: #F6FAFF !important;
    }

    ::placeholder {
      font-size: 14px;
      color: #B8BECA;
    }

    .title {
      font-weight: 500;
      font-size: 16px;
      color: #1A1B1C;
      width: 100%;
      text-align: center;
      margin: 30px 0 20px 0;
    }

    .van-image {
      width: 10px;
      height: 10px;
      position: absolute;
      right: 18px;
      top: 18px;
    }

    :deep .van-form {
      min-height: 265px;
    }

    .button {
      color: #FFFFFF;
      font-size: 14px;
      width: 285px;
      height: 44px;
      background: #0094FF;
      border-radius: 23px;
      margin: auto;
      display: flex;
      justify-content: center;
      margin-top: 10px;
    }
  }
}

.wrappers {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;

  .wrapper_div {
    width: 315px;
    height: 500px;
    background-color: #fff;
    border-radius: 5px;
    position: relative;
    box-sizing: border-box;
    padding: 0 15px;

    .mechanism_conent {
      width: 285px;
      height: 280px;
      background: linear-gradient(#FBFCFE 0%, #EFF6FF 100%);
      border-radius: 10px;
      margin-top: 15px;
      box-sizing: border-box;
      padding: 20px 15px;

      :deep(.van-cell-group--inset) {
        margin: 0 !important;
        margin-bottom: 20px !important;
        background: transparent !important;
      }

      :deep(.van-cell) {
        padding: 0 !important;
        background: none !important;
        background: transparent !important;
      }

      :deep(.van-field__control) {
        font-weight: 400 !important;
        font-size: 14px !important;
        color: #8492AD !important;

      }

      :deep(.van-field__button) {
        padding-left: 0px !important;
      }

      :deep .van-field__control {
        background: transparent !important;
      }

      .mechanism_conent_item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        margin-bottom: 20px;

        .labels {
          font-weight: 400;
          font-size: 14px;
          color: #1A1B1C;
        }

        .value {
          font-weight: 400;
          font-size: 14px;
          color: #8492AD;
        }
      }
    }

    .close {
      width: 10px;
      height: 10px;
      position: absolute;
      right: 18px;
      top: 18px;
    }

    .column {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;


      .lable {
        font-weight: 400;
        font-size: 14px;
        color: #1A1B1C;

      }

      .value {
        width: 214px;
        height: 36px;
        background: #F2F3F5;
        border-radius: 18px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-weight: 400;
        font-size: 14px;
        color: #1A1B1C;
        box-sizing: border-box;
        padding: 0 15px;

        .van-image {
          width: 10px;
          height: 6px;


        }
      }
    }

    :deep .van-cell:after {
      display: none;
    }

    .label {
      font-weight: 400;
      font-size: 14px;
      color: #000000;
      padding-left: 16px;
    }

    :deep .van-field__control {
      background: #F6FAFF !important;
      // height: 40px !important;

    }

    ::placeholder {
      font-size: 14px;
      color: #B8BECA;
    }

    .dates {
      :deep .van-field__control {
        height: 40px !important;
      }
    }

    .title {
      font-weight: 500;
      font-size: 16px;
      color: #1A1B1C;
      width: 100%;
      text-align: center;
      margin: 30px 0 20px 0;
    }



    :deep .van-form {
      min-height: 265px;
    }

    .buttons {
      width: 285px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      text-align: center;
      line-height: 44px;
      position: absolute;
      bottom: 10px;

      .cancel {
        width: 135px;
        height: 44px;
        border-radius: 23px;
        border: 1px solid #0094FF;
        font-weight: 400;
        font-size: 16px;
        color: #0094FF;
      }

      .save {
        width: 135px;
        height: 44px;
        background: #0094FF;
        border-radius: 23px;
        font-weight: 400;
        font-size: 16px;
        color: #FFFFFF;
      }
    }

    .describe {
      font-weight: 400;
      font-size: 14px;
      color: #8492AD;
      margin-bottom: 10px;
    }



  }

}

.wrapper_qualifications {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;

  .wrapper_div {
    width: 315px;
    height: 280px;
    background-color: #fff;
    border-radius: 5px;
    position: relative;
    box-sizing: border-box;
    padding: 0 15px;

    .close {
      width: 10px;
      height: 10px;
      position: absolute;
      right: 18px;
      top: 18px;
    }

    .describe {
      font-weight: 400;
      font-size: 14px;
      color: #8492AD;
      margin-bottom: 10px;
    }

    .title {
      font-weight: 500;
      font-size: 16px;
      color: #1A1B1C;
      width: 100%;
      text-align: center;
      margin: 30px 0 20px 0;
    }

    .column {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;


      .lable {
        font-weight: 400;
        font-size: 14px;
        color: #1A1B1C;

      }

      .value {
        width: 214px;
        height: 36px;
        background: #F2F3F5;
        border-radius: 18px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-weight: 400;
        font-size: 14px;
        color: #1A1B1C;
        box-sizing: border-box;
        padding: 0 15px;

        .van-image {
          width: 10px;
          height: 6px;
        }
      }
    }

    .buttons {
      width: 285px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      text-align: center;
      line-height: 44px;
      position: absolute;
      bottom: 10px;

      .cancel {
        width: 135px;
        height: 44px;
        border-radius: 23px;
        border: 1px solid #0094FF;
        font-weight: 400;
        font-size: 16px;
        color: #0094FF;
      }

      .save {
        width: 135px;
        height: 44px;
        background: #0094FF;
        border-radius: 23px;
        font-weight: 400;
        font-size: 16px;
        color: #FFFFFF;
      }
    }

  }
}
</style>